package com.cskaoyan._03equals.notice;

/**
 * @description:
 * @author: 景天
 * @date: 2023/2/14 16:15
 **/
/*
如果类中有引用数据类型成员变量，
需要去调用它们的equals方法完成比较。这就意味着还需要重写这个类的equals方法。
 */
public class Demo2 {
    public static void main(String[] args) {
        Student s1 = new Student("zs", "13666666666", new Subject("化学"));
        Student s2 = new Student("zs", "13666666666", new Subject("化学"));
        System.out.println(s1.equals(s2));
    }
}

class Student{
    String name;
    String phone;
    Subject subject;

    public Student(String name, String phone, Subject subject) {
        this.name = name;
        this.phone = phone;
        this.subject = subject;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (name != null ? !name.equals(student.name) : student.name != null) return false;
        if (phone != null ? !phone.equals(student.phone) : student.phone != null) return false;
        return subject != null ? subject.equals(student.subject) : student.subject == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (phone != null ? phone.hashCode() : 0);
        result = 31 * result + (subject != null ? subject.hashCode() : 0);
        return result;
    }
}

class Subject{
    String name;

    public Subject(String name) {
        this.name = name;
    }

    // 这个类也要重写equals方法

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Subject subject = (Subject) o;

        return name != null ? name.equals(subject.name) : subject.name == null;
    }

    @Override
    public int hashCode() {
        return name != null ? name.hashCode() : 0;
    }
}